﻿using RBAC.LuFang.Domain;
using RBAC.LuFang.Domain.DTO;
using RBAC.LuFang.Repository.lnterface;
using System.Net.Http;
using System.Security.Claims;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace RBAC.LuFang.Domin.Services
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly IProvincesRepository _provincesRepository;
        private readonly ITheCityRepository _theCityRepository;
        private readonly ICountyRepository _countyRepository;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly IRoleRepository _RoleRepository;
        //构造函数
        public UserService(IUserRepository userRepository, IProvincesRepository provincesRepository, ITheCityRepository theCityRepository, ICountyRepository countyRepository, IUserRoleRepository userRoleRepository, IRoleRepository roleRepository)
        {
            _userRepository = userRepository;
            _provincesRepository = provincesRepository;
            _theCityRepository = theCityRepository;
            _countyRepository = countyRepository;
            _userRoleRepository = userRoleRepository;
            _RoleRepository = roleRepository;
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<int> AddUser(UserInfo user)
        {
            try
            {
                user.password = "12345678";
                user.addName = "张三";
                user.addDate =DateTime.Now;
                var list =(await _userRepository.GetAllAsync()).Where(x=>x.userName==user.userName);
                if (list.Count()>0)
                {
                    return -1;//用户名已经存在
                }
                return await _userRepository.GetAddAsync(user);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 显示省
        /// </summary>
        /// <returns></returns>
        public async Task<List<Province>> GetProvince()
        {
            try
            {
                return await _provincesRepository.GetAllAsync();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 显示市
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public Task<List<TheCity>> GetTheCity(int pid)
        {
            try
            {
                return _theCityRepository.Get(x=>x.provinceID==pid);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 显示县
        /// </summary>
        /// <param name="thecityId"></param>
        /// <returns></returns>
        public async Task<List<County>> GetCounty(int thecityId)
        {
            try
            {
                return await _countyRepository.Get(x => x.theCityID == thecityId);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="uname"></param>
        /// <param name="upwd"></param>
        /// <returns></returns>
        public async Task<useloginDTO> GetLogin(string uname, string upwd)
        {
            try
            {
                useloginDTO dto = new useloginDTO();
                var res = (await _userRepository.GetAllAsync()).Where(x => x.userName == uname).FirstOrDefault();
                if (res == null)
                {
                    dto.code = -1;
                    dto.uid = 0;
                    return dto;//用户名不存在
                }
                if (res.password == upwd)
                {
                    dto.code = 1;
                    dto.uid = res.userInfoID;
                    var list = (await _userRoleRepository.GetAllAsync()).Where(x => x.userInfoID == dto.uid && x.IsDel==false);
                    var array=new List<int>();
                    foreach (var item in list)
                    {
                        array.Add(item.RoleId);
                    }
                    dto.rid = string.Join(",",array);
                    return dto;//登录成功
                }
                dto.code = -2;
                dto.uid = 0;
                return dto;//密码错误
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 显示用户列表
        /// </summary>
        /// <returns></returns>
        public async Task<page> GetUser(int pageindex,int pagesize, string? uname)
        {
            try
            {
                page page = new page();
                var arr = await _userRoleRepository.GetAllAsync();//用户角色
                var role = await _RoleRepository.GetAllAsync();//角色

                var list = from a in await _userRepository.GetAllAsync()//用户
                           join b in await _provincesRepository.GetAllAsync()//省
                           on a.provinceID equals b.provinceID
                           join c in await _theCityRepository.GetAllAsync()//市
                           on a.theCityID equals c.theCityID
                           join d in await _countyRepository.GetAllAsync()//县
                           on a.countyID equals d.countyID
                           where a.IsDel==false
                           select new UserInfoDTO
                           {
                               userInfoID=a.userInfoID,
                               userName=a.userName,
                               userSex=a.userSex,
                               userAddress=a.userAddress,
                               addName = a.addName,
                               addDate=a.addDate,
                               updName=a.updName,
                               updDate=a.updDate,
                               provinceName = b.provinceName,
                               theCityName=c.theCityName,
                               countyName=d.countyName,
                               value=(from q in arr
                                     join w in role on q.RoleId equals w.RoleId
                                     where q.userInfoID==a.userInfoID && q.IsDel==false
                                     select new Role
                                     {
                                         RoleName=w.RoleName
                                     }).ToList()
                           };
                if (!string.IsNullOrEmpty(uname))
                {
                    list = list.Where(x => x.userName.Contains(uname)).ToList();
                }
                page.sumcount = list.Count();
                page.lastpage = (int)Math.Ceiling(page.sumcount * 1.0 / pagesize);
                page.userlist = list.OrderByDescending(x => x.addDate).Skip((pageindex - 1) * pagesize).Take(pagesize).ToList();
                return page;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 用户反填
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<UserInfo> GetByid(int id)
        {
            try
            {
                return await _userRepository.GetByidAsync(id);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<int> UpdUser(UserInfo user)
        {
            try
            {
                user.updName = "李四";
                user.updDate = DateTime.Now;
                return await _userRepository.GetUpd(user);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 用户删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DelUser(int id)
        {
            try
            {
                var res = await _userRepository.GetByidAsync(id);
                res.IsDel= true;
                return await _userRepository.GetUpd(res);
            }
            catch (Exception)
            {

                throw;
            }
        }
       




    }
}
